import {messages, queryCurrencyPrecision, dealListTag, invoiceAmountChange} from 'share/common';
import React from 'react';
import ExportModal from 'components/template/export-modal/export-modal';
import { connect } from 'react-redux';
import { message, Popover, Alert, Tabs, Select, Tag, Checkbox, Button } from 'antd';

const TabPane = Tabs.TabPane;
const Option = Select.Option;
import moment from 'moment';
import menuRoute from 'routes/menuRoute';
import constants from 'share/constants';
import financeViewService from 'containers/financial-management/corporate-payment-report-view/corporate-payment-report-view.service';
import CostCenterSearchForm
  from 'components/template/cost-center-search-form/cost-center-search-form';
import 'styles/financial-management/expense-view/expense-view.scss';
import BatchDownload from './batch-download';
import AdvancedTable from 'components/advanced-table';
import GenerateBatch from './generate-batch';
import selectorData from 'share/selectorData';
import SelectBatchNumber from './select-batch-number';
import NumberRange from 'containers/financial-management/expense-view/component/number-range';
import openSlideFrame from 'share/openSlideFrame';
import { origDocument, expensePartner, labelIds } from 'containers/financial-management/expense-view/component/func-component';
import Department from 'components/template/department';

class FinanceView extends React.Component {

  columns = [{
    title: messages('common.user.id')/*工号*/, dataIndex: 'employeeID'
  }, {
    title: messages('common.applicant')/*申请人*/, dataIndex: 'applicant'
  }, {
    title: messages('common.submit.date')/*提交日期*/,
    dataIndex: 'lastSubmittedDate',
    width: 95,
    render: (date, record) => moment(date || record.createDate)
      .format('YYYY-MM-DD'),
    sorter: true
  }, {
    title: messages('finance-9.key3')/*供应商名称*/, dataIndex: 'corpSupplierName',
    render: value => <Popover content={value}>{value}</Popover>
  }, {
    title: messages('expense-1.key410')/*记账日期*/, dataIndex: 'bookDate', render: value => value ? moment(value).format('YYYY-MM-DD') : '-'
  }, {
    title: messages('expense-1.key607')/*单据类型*/, dataIndex: 'formName',
    render: value => <Popover content={value}>{value}</Popover>,
    sorter: true
  }, {
    title: messages('common.document.code')/*单号*/, dataIndex: 'businessCode',
    render: (value, record) => (
      <Popover
        content={record.parentBusinessCode ? `${record.parentBusinessCode} - ${value}` : value}>
        {record.parentBusinessCode ? `${record.parentBusinessCode} - ${value}` : value}
      </Popover>
    ), sorter: true
  }, {
    title: messages('expense-1.key137')/*事由说明temp*/, dataIndex: 'title', width: 120,
    render: value => <Popover content={value} placement="topLeft">{value}</Popover>
  }, {
    title: messages('finance-9.key4')/*到票金额*/, dataIndex: 'totalAmount',  align: 'right',
    render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)),
    width: '7%'
  }, {
    title: messages('finance-9.key5')/*支付金额*/, dataIndex: 'paymentTotalAmount', align: 'right',
    render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)),
    width: '7%'
  }, {
    title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode', width: 48
  },
    {
      title: messages('expense-1.key608')/*寄单状态*/,
      dataIndex: 'sendBillStatus',
      width: 48,
      hide: true,
      render: value => constants.getTextByValue(String(value + ''), 'sendBillOptions', 'label'),
    },
    {
      title: messages('expense-1.key413')/*快递单号*/,
      dataIndex: 'deliveryCode',
      hide: true,
      render: value => value ? <Popover content={value} placement="topLeft">{value}</Popover> : '-'
    },
    {
    title: messages('expense-1.key609')/*收单状态*/,
    dataIndex: 'receiveStatus',
    width: 48,
    hide: true,
    render: value => constants.getTextByValue(String(value + ''), 'receiptOptions', 'label'),
  }, {
    title: messages('expense-1.key601')/*凭证编号*/,
    dataIndex: 'origDocumentSequence',
    width: '7%',
    render: value => value ? <Popover content={value} placement="topLeft">{value}</Popover> : '-'
  }, {
    title: messages('expense-1.key610')/*批量打印批次号*/, dataIndex: 'expenseReportBatchId',
    render: value => value ? <Popover content={value} placement="topLeft">{value}</Popover> : '-'
  }, {
      title: messages('expense-1.key611')/*付款日期*/,
      dataIndex: 'realPaymentDate',
      render: value => value
        ? <Popover
          content={moment(value).format('YYYY-MM-DD HH:mm:ss')} placement="topLeft">
          {moment(value).format('YYYY-MM-DD HH:mm:ss')}
        </Popover>
        : '-'
  }, {
    title: messages('common.column.status')/*状态*/, dataIndex: 'status',
    width: this.props.language.code === 'zh_cn' ? '8%' : '13%',
    render: (value, record) => (
      <Tag color={
        constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus', 'color') ||
        constants.getTextByValue(String(value), 'documentStatus', 'color')
      }>
        {
          constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus') ||
          constants.getTextByValue(String(value), 'documentStatus')
        }
      </Tag>
    )
  }, {
    title: messages('common.operation')/*操作*/, dataIndex: 'operation', width: 100,
    render: (value, record) => (
      <GenerateBatch
        mode='single'
        params={{entityOID: record.entityOID, entityType: record.entityType}}
        needPreventDefault
        isExpenseReportView
        btnProps={{
          name: messages('common.print')/*打印*/,
          href: ''
        }}
      />)
  }];

  autoAuditOptions = [
    { label: messages('common.all')/*全部*/, value: null },
    { label: messages('common.yes')/*是*/, value: true },
    { label: messages('common.no')/*否*/, value: false }
  ];

  state = {
    sort: '',
    searchParams: {},
    tabKey: 'view'
  };

  statusOptions = [{
    label: messages('expense-1.key474')/*审批中*/, value: 'submitted'
  }, {
    label: messages('expense-1.key612')/*已通过*/, value: 'approval_pass'
  }, {
    label: messages('expense-1.key373')/*已驳回*/, value: 'approval_reject'
  }, {
    label: messages('expense-1.key613')/*审核通过*/, value: 'audit_pass'
  }, {
    label: messages('expense-1.key614')/*审核驳回*/, value: 'audit_reject'
  }, {
    label: messages('expense-1.key615')/*付款中*/, value: 'payment_in_process'
  }, {
    label: messages('expense-1.key616')/*已付款*/, value: 'finance_loan'
  }];

  searchForm = [
    {
      id: 'formOIDs',
      component: 'MultiSelectorV2',
      label: messages('expense-1.key617')/*表单类型*/,
      props: {
        type: 'authority_form',
        params: { entityType: 3004 },
        labelKey: 'formName',
        isShowSelectAll: true
      },
      parser: value => ({
        formOIDs: value ? value.map(item => item.formOID) : null
      })
    }, {
    id: 'userOID', label: messages('expense-1.key618')/*申请人姓名/工号*/,
    component: 'Selector',
    props: {
      placeholder: messages('expense-1.key619')/*请输入工号/姓名/手机号/部门/邮箱/职位*/,
      type: 'user',
      selectorItem: {
        ...selectorData['user'],
        url: `/api/users/v3/search`,
        label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
            (`（${record.status === 1002 ?
                messages('expense-1.key620')/*待离职员工*/ :
                messages('expense-1.key621')/*离职员工*/}）`
            ) :
            ''
        )}`)
      },
      searchIfKeywordIsNull: false
    },
  }, {
    id: 'businessCode', label: messages('expense-1.key622')/*单据ID*/,
    component: 'Input',
  }, {
    id: 'departmentOIDs', label: messages('common.department')/*部门*/, component: <Department/>,
    parser: value => ({
      departmentOIDs: value ? value.map(item => item.departmentOID) : null
    }), tagParser: value => (value.map(item => item.title).join(','))
  }, {
    id: 'submittedDate', label: messages('common.submit.date')/*提交日期*/,
    component: 'DateRangePicker',
    initialValue: [moment()
      .subtract(1, 'month'), moment()],
    parser: value => ({
      beginDate: value && value[0] ? moment(value[0])
        .format('YYYY-MM-DD 00:00:00') : null,
      endDate: value && value[1] ? moment(value[1])
        .format('YYYY-MM-DD 23:59:59') : null
    })
  }, {
    id: 'approvalDate', label: messages('expense-1.key623')/*审批日期*/,
    component: 'DateRangePicker',
    parser: value => ({
      approvalStartDate: value && value[0] ? moment(value[0])
        .format('YYYY-MM-DD 00:00:00') : null,
      approvalEndDate: value && value[1] ? moment(value[1])
        .format('YYYY-MM-DD 23:59:59') : null
    })
  }, {
    id: 'auditedApprovalDate', label: messages('expense-1.key624')/*审核日期*/,
    component: 'DateRangePicker',
    parser: value => ({
      auditedApprovalStartDate: value && value[0] ? moment(value[0])
        .format('YYYY-MM-DD 00:00:00') : null,
      auditedApprovalEndDate: value && value[1] ? moment(value[1])
        .format('YYYY-MM-DD 23:59:59') : null
    })
  }, {
      id: 'payDate', label: messages('expense-1.key611')/*付款日期*/,
      component: 'DateRangePicker',
      parser: value => ({
        realPaymentStartDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
        realPaymentEndDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
      })
  }, {
    component: 'Chooser',
      id: 'selectCompanyOIDs',
      label: messages('request-4.key12')/*公司*/,
      props: {
        labelKey: 'name',
        valueKey: 'companyOID',
        type: 'permission_company',
        listExtraParams:{enabled: true}
      },
      parser: value => ({
        selectCompanyOIDs: value ? value.map(item => item.companyOID) : null
      }),
      JSONObjectFormatterParams: ['departmentName', 'companyOID']
    }, {
    id: 'autoAudit', label: messages('expense-1.key626')/*自动审核通过*/,
    component: <Select placeholder={messages('expense-1.key604')/*请选择temp*/} style={{ width: '100%' }}>
      {this.autoAuditOptions.map(item => <Option key={item.value}>{item.label}</Option>)}
    </Select>,
    parser: value => {
      let result = {
        autoAudit: null
      };
      if (typeof value === 'string') {
        switch (value) {
          case 'true':
            result.autoAudit = true;
            break;
          case 'false':
            result.autoAudit = false;
            break;
          case 'null':
            result.autoAudit = null;
            break;
        }
      }
      return result;
    },
    tagParser: value => this.autoAuditOptions.find(item => (item.value + '') === value).label
  }, {
    id: 'searchCostCenterCommands', label: messages('expense-1.key627')/*成本中心*/,
    component: <CostCenterSearchForm title={messages('expense-1.key627')/*成本中心*/}/>,
    tagParser: value => messages('common.total.selected',{arg1: value.length})/*已选 {arg1} 条*/
  }, {
    id: 'batchNumber', label: messages('expense-1.key610')/*批量打印批次号*/,
    component: <SelectBatchNumber/>,
    parser: value => {
      if (!value) {
        return null;
      } else {
        const { existsExpenseReportBatchId, expenseReportBatchId } = value;
        return existsExpenseReportBatchId && !expenseReportBatchId ? null : (
          !existsExpenseReportBatchId ?
            { existsExpenseReportBatchId } :
            { expenseReportBatchId, existsExpenseReportBatchId }
        );
      }
    },
    tagParser: ({ existsExpenseReportBatchId, expenseReportBatchId }) =>
      !existsExpenseReportBatchId ?
        messages('expense-1.key602')/*为空*/ :
        expenseReportBatchId
  }, labelIds() , {
    id: 'sendBillStatus',
    label: messages('expense-1.key608')/*寄单状态*/,
    component: (
      <Select allowClear placeholder={messages('expense-1.key604')/*请选择temp*/} style={{ width: '100%' }}>
        {constants.sendBillOptions.map(item => <Option key={item.value}>{item.label}</Option>)}
      </Select>
    ),
    tagParser: value => value ? constants.sendBillOptions.filter(item => item.value == value)[0].label : null
  }, {
    id: 'billingDateRange', label: messages('expense-1.key628')/*寄单日期*/,
    component: 'DateRangePicker',
    parser: value => ({
      sendBillStartDate: value && value[0] ? moment(value[0])
        .format('YYYY-MM-DD 00:00:00') : null,
      sendBillEndDate: value && value[1] ? moment(value[1])
        .format('YYYY-MM-DD 23:59:59') : null
    })
  }, {
    id: 'sendBillUserOIDs',
    label: messages('expense-1.key629')/*寄单人*/,
    component: 'Chooser',
    props: {
      type: 'loan-max-users',
      labelKey: 'fullName',
      valueKey: 'userOID',
    },
    parser: value => ({
      sendBillUserOIDs: value ? value.map(item => item.userOID) : null
    }),
    JSONObjectFormatterParams: ['fullName', 'userOID']
  }, {
    id: 'financeApprovalOIDs',
    label: messages('expense-1.key630')/*审核通过人*/,
    component: 'Chooser',
    props: {
      type: 'finance-auditable-users',
      labelKey: 'fullName',
      valueKey: 'userOID'
    },
    parser: value => ({
      financeApprovalOIDs: value ? value.map(item => item.userOID) : null
    }),
    JSONObjectFormatterParams: ['fullName', 'userOID']
  }, {
    id: 'receiveStatus',
    label: messages('expense-1.key609')/*收单状态*/,
    component: (
      <Select allowClear placeholder={messages('expense-1.key604')/*请选择temp*/} style={{ width: '100%' }}>
        {constants.receiptOptions.map(item => <Option key={item.value}>{item.label}</Option>)}
      </Select>
    ),
    tagParser: value => value ? constants.receiptOptions.filter(item => item.value == value)[0].label : null
  }, {
    id: 'financeReceiptDateRange', label: messages('expense-1.key631')/*收单日期*/,
    component: 'DateRangePicker',
    parser: value => ({
      financeReceiveStartDate: value && value[0] ? moment(value[0])
        .format('YYYY-MM-DD 00:00:00') : null,
      financeReceiveEndDate: value && value[1] ? moment(value[1])
        .format('YYYY-MM-DD 23:59:59') : null
    })
  },
    {
      id: 'financeReceiverOIDs',
      label: messages('expense-1.key632')/*收单人*/,
      component: 'Chooser',
      props: {
        type: 'loan-max-users',
        labelKey: 'fullName',
        valueKey: 'userOID',
      },
      parser: value => ({
        financeReceiverOIDs: value ? value.map(item => item.userOID) : null
      }),
      JSONObjectFormatterParams: ['fullName', 'userOID']
  }, {
      id: 'bookDate', label: messages('expense-1.key410')/*记账日期*/, component: 'DateRangePicker',
      parser: value => ({
        bookStartDate: value && value[0] ? moment(value[0])
          .format('YYYY-MM-DD 00:00:00') : undefined,
        bookEndDate: value && value[1] ? moment(value[1])
          .format('YYYY-MM-DD 23:59:59') : undefined
      })
    }, origDocument,
    {
    id: 'reimbursementBatchId', label: messages('expense-1.key633')/*付款批次号*/,
    component: 'Selector',
    props: {
      placeholder: messages('common.please.input')/*请输入*/ + messages('expense-1.key633')/*付款批次号*/,
      type: 'reimbursement_batch',
      params: {
        batchType: 3001,
        roleType: 'TENANT'
      }
    },
    JSONObjectFormatterParams: ['reimbursementBatchName', 'id']
  }, {
    id: 'numberRange',
    label: messages('expense-1.key634')/*金额范围*/,
    component: <NumberRange allowInputZero />,
    parser: value => ({
      minTotalAmount: value && (value[0] || value[0] === 0) ? value[0] : null,
      maxTotalAmount: value && (value[1] || value[1] === 0) ? value[1] : null
    }),
    tagParser: value => value && ((value[0] || value[0] === 0) || (value[1] || value[1] === 0)) &&
      `${(value[0] || value[0] === 0) ? `${value[0]}` : ''} ~ ${(value[1] || value[1] === 0) ? `${value[1]}` : ''}`
  },{
    id: 'corpSupplierId', label: messages('finance-9.key1')/*供应商*/,
    component: 'Chooser',
    props: {
      type: 'vendor_account',
      labelKey: 'venNickname',
      valueKey: 'id',
      listExtraParams: {
        companyOid: this.props.company.companyOID
      },
      dataIndex: 'corpSupplierId'
    },
    parser: value => ({
      corpSupplierId: value ? value.map(item => item.id) : null
    })
  }, {
    id: 'deliveryCode', label: messages('expense-1.key413')/*快递单号*/,
    component: 'Input',
  }, {
    id: 'status', label: messages('common.column.status')/*状态*/,
    component: (
      <Checkbox.Group>
        {this.statusOptions.concat(this.props.profile['finance.payment.cancel'] ? {
          label: messages('expense-1.key635')/*取消支付*/,
          value: 'pay_cancel'
        } : [])
          .map(item => (
            <Checkbox key={item.value} value={item.value}>{item.label}</Checkbox>
          ))}
      </Checkbox.Group>
    ),
    tagParser: value => this.statusOptions.filter(item => value.find(key => item.value === key))
      .map(item => item.label)
      .join(','),
    row: true
  }];

  service = (page, size, searchParams) => {
    const { sort } = this.state;
    if (sort) {
      searchParams.sorts = {
        property: sort.split(',')[0],
        direction: sort.split(',')[1]
      };
    }
    searchParams.entityType = 1002;
    //依次检测时间字段，查询时间跨度不能超过12个月
    const sy = moment(searchParams.realPaymentStartDate).get('year');
    const ey = moment(searchParams.realPaymentEndDate).get('year');
    const sm = moment(searchParams.realPaymentEndDate).get('month');
    const em = moment(searchParams.realPaymentEndDate).get('month');
    if ((ey * 12 + em) - (sy * 12 + sm) > 12) {
      return new Promise((res, rej) => {
        const content = messages('expense-1.key636')/*查询时间跨度不超过12个月！*/;
        message.warning(content);
        rej(new Error(content));
      });
    }
    searchParams.corporateFlag = true;
    return financeViewService.getFinanceViewList(page, size, searchParams);
  };


  handleRowClick = (record) => {
    openSlideFrame.openCorporateReportDetail({
      expenseReportOID: record.entityOID,
      entry: 'view'
    }, {
      noPadding: true
    }, this);
  };

  handleSortChange = (pagination, filter, sorter) => {
    let sort = '';
    if (sorter.order) {
      sort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`;
    }
    this.setState({ sort }, this.advancedTableRef.getList);
  };

  onGetData = (dataSource, pagination, searchParams) => {
    this.setState({ searchParams, dataSource });
  };

  goScanGunView = () => {
    this.context.router.push(menuRoute.getRouteItem('scan-gun-view').url.replace(':pageFrom', 'vendorPayment'))
  };

  render() {
    const { searchParams, tabKey, dataSource } = this.state;
    return (
      <div className="expense-view full-height-page">
        <Button className='expense-view-mode' onClick={this.goScanGunView}>{messages('expense-1.key637')/*扫码枪查看*/}</Button>
        <Tabs activeKey={tabKey} onChange={tabKey => this.setState({ tabKey })}>
          <TabPane tab={messages('finance-9.key104')/*对公支付单查看*/} key="view">
            <AdvancedTable
              index
              onRef={ref => this.advancedTableRef = ref}
              title={messages('finance-9.key104')/*对公支付单查看*/}
              columns={this.columns}
              searchForm={this.searchForm}
              service={this.service}
              onRow={record => ({
                onClick: () => this.handleRowClick(record)
              })}
              expandedRowRender={dealListTag}
              expandAll
              onChange={this.handleSortChange}
              rowKey={record => record.entityOID}
              tableName='expense-view'
              onGetData={this.onGetData}
              pinnedList={['businessCode', 'userOID', 'status']}
              notLoadWhenMount
              header={<Alert
                className="notice"
                type="info"
                showIcon
                message={<div
                  dangerouslySetInnerHTML={{
                    __html: messages('expense-1.key639')/*列表中<span class='color-blue'>批量打印批次号为空</span>的数据将会生成批次。*/
                    /*列表中<span class='color-blue'>批量打印批次号为空</span>的数据将会生成批次。*/
                  }}/>}
              />}
              footer={
                <GenerateBatch
                  params={searchParams}
                  isExpenseReportView
                  onOk={() => this.setState({ tabKey: 'download' })}
                  btnProps={{
                    disabled: !(dataSource && dataSource.length),
                    name: messages('expense-1.key641')/*生成批次*/,
                    type: 'primary'
                  }}
                />
              }
            >
            </AdvancedTable>
          </TabPane>
          <TabPane tab={messages('expense-1.key642')/*批次下载*/} key="download">
            <BatchDownload tabKey={tabKey}/>
          </TabPane>
        </Tabs>
      </div>
    );
  }
}

FinanceView.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    language: state.main.language,
    profile: state.login.profile
  };
}

export default connect(mapStateToProps)(FinanceView);
